package org.tio.sitexxx.service.service.qj;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.sitexxx.service.cache.CacheConfig;
import org.tio.sitexxx.service.cache.Caches;
import org.tio.sitexxx.service.model.main.Member;
import org.tio.sitexxx.service.vo.Const;
import org.tio.utils.cache.CacheUtils;
import org.tio.utils.cache.FirsthandCreater;
import org.tio.utils.cache.ICache;

import java.util.Map;

public class MemberService {
    private static Logger log	= LoggerFactory.getLogger(MemberService.class);
    public static final MemberService me	= new MemberService();
    final Member dao	= new Member().dao();
    /**
     * 保存数据
     * @param demo
     * @return
     */
    public boolean save(Member demo) {
        return demo.save();
    }

    /**
     * 修改数据
     * @param demo
     * @return
     */
    public boolean update(Member demo) {
        return demo.update();
    }
    /**
     * 查找member
     */
    public Member getMember(Map<String,Object>map){
            ICache cache  = Caches.getCache(CacheConfig.DEMO_CACHE);
        String key=null;
        if(map.get("id")==null){
            key =map.get("openid").toString();
        }else{
            key=map.get("id").toString();
        }
        boolean putTempToCacheIfNull  = false;
        Member member = CacheUtils.get(cache, key, putTempToCacheIfNull, new FirsthandCreater<Member>() {
            @Override
            public Member create() {
                String sqlid = "member.getmember";
                String db = Const.Db.TIO_SITE_MAIN;
                Kv cond=Kv.create().set(map);
                SqlPara sqlPara = Db.use("tio_sitex_main").getSqlPara(sqlid,cond);
                Record record = Db.use(db).findFirst(sqlPara);
                if(record==null){
                    return null;
                }
                Member member =JSON.parseObject(JSON.toJSONBytes(record.getColumns()),Member.class);
                return member;
            }
        });


       return member;
    }

    /**
     * 不带缓存的用户信息
     * @param map
     * @return
     */
    public Member getMemberWithoutCatch(Map<String,Object>map){
        String sqlid = "member.getmember";
        String db = Const.Db.TIO_SITE_MAIN;
        Kv cond=Kv.create().set(map);
//        Member list = Member.dao.findFirst(sql, openid);
        SqlPara sqlPara = Db.use(db).getSqlPara(sqlid,cond);
        Record record = Db.use(db).findFirst(sqlPara);
        if(record==null){
            return null;
        }
        Member member =JSON.parseObject(JSON.toJSONBytes(record.getColumns()),Member.class);
        return member;

    }
}
